home *** CD-ROM | disk | FTP | other *** search
/ Tricks of the Mac Game Programming Gurus / TricksOfTheMacGameProgrammingGurus.iso / More Source / Libraries / VideoToolbox 95.04.18 / VideoToolboxSources / GDVideo.c < prev    next >
Encoding:
Text File  |  1995-04-11  |  60.4 KB  |  1,630 lines  |  [TEXT/MMCC]

  1. /* 
  2. GDVideo.c
  3. Copyright © 1989-1994 Denis G. Pelli
  4.  
  5. Complete set of routines to control video drivers directly, bypassing
  6. QuickDraw's Color and Palette Managers. There is a separate function call for
  7. each of the Control and Status Calls (csc) implemented by video drivers. They
  8. are described in Designing Cards and Drivers, 3rd Ed., chapter 9. A few new
  9. calls are documented in the Display Device Driver Guide Developer Note, which
  10. appeared on the January '94 Developer CD.
  11.  
  12. This file also contains several other helpful routines that deal with video
  13. device drivers. For background, read “Video synch”.
  14.  
  15. THE MORE-USEFUL (HIGH-LEVEL) ROUTINES: (in alphabetical order)
  16.  
  17. char *GDCardName(GDHandle device);
  18. Returns the address of a C string containing the name of the video card. You
  19. should call DisposePtr() on the returned string when you no longer need it.
  20. Takes about 1.5 ms because Apple's slot routines are very slow. 
  21.  
  22. short GDClutSize(GDHandle device);
  23. Returns the number of entries in the video driver's clut in the current video
  24. mode (i.e. current pixel size). VideoToolbox.h defines a preprocessor macro
  25. GDCLUTSIZE(device) that expands to equivalent inline code.
  26.  
  27. long GDColors(GDHandle device)
  28. Number of colors, in the current mode.
  29.  
  30. short GDDacSize(GDHandle device)
  31. Figures out how many bits in the video dac.
  32.  
  33. OSErr GDGetDisplayMode(GDHandle device,unsigned long *displayModeIDPtr
  34.     ,unsigned short *modePtr,unsigned short *pagePtr,Ptr *baseAddrPtr);
  35. Calls cscGetCurMode, documented in Apple's new Display Device Driver Guide
  36. Developer Note on the January '94 Developer CD. The "display mode ID" is a new
  37. parameter, to support multi-resolution displays. Each display mode may have
  38. multiple pixel depths (which, confusingly, have also been called "modes"). This
  39. call will only be useful if the Display Manager is present (requires PowerPC or
  40. System 7.5) and if you're using the Display Manager, which is documented in a
  41. chapter in Inside Macintosh:Advanced Color Imaging, which thus far has appeared
  42. only in draft form on the December '94 Developer CD. The call returns an error
  43. if the video driver does not support the Display Manager. UNTESTED!!
  44.  
  45. OSErr GDGetEntries(GDHandle device,short start,short count,ColorSpec *table);
  46. Calls cscGetEntries. This is much as you'd expect after reading GDSetEntries
  47. below. Note that unless the gamma table is linear, the values returned may not
  48. be the same as those originally passed by GDSetEntries. So call
  49. GDUncorrectedGamma first. Try the demo TimeVideo.
  50.  
  51. OSErr GDGetGamma(GDHandle device,GammaTbl **myGammaTblHandle);
  52. Calls cscGetGamma. Returns a pointer to the Gamma table in the specified video
  53. device. (I.e. you pass it a pointer to your pointer, a handle, which it uses to
  54. load your pointer.)
  55.  
  56. OSErr GDGetPageCnt(GDHandle device,short mode,short *pagesPtr);
  57. Calls cscGetPageCnt. Called "GetPages" in Designing Cards and Drivers, 3rd Ed.
  58. You tell it which mode you're interested in. It tells you how many pages of
  59. video ram are available in that mode.
  60.  
  61. Boolean GDHasMode(GDHandle device,short mode,short *pixelSizePtr,short *pagesPtr);
  62. Returns 0 if no such video mode, returns 1 if mode is available.
  63. If pixelSizePtr is not NULL, then sets *pixelSizePtr to pixelSize or -1 if unknown.
  64. If pagesPtr is not NULL, then sets *pagesPtr to pages.
  65.  
  66. unsigned char *GDName(GDHandle device);
  67. Returns a pointer to the name of the driver (a pascal string). This is quick.
  68. The string is part of the driver itself, so don't modify it or try to dispose of it.
  69.  
  70. unsigned char *GDNameStr(GDHandle device);
  71. Returns a pointer to the name of the driver, as a C string. 
  72. The string is static, and will be overwritten by the next call to GDNameStr().
  73.  
  74. ColorSpec *GDNewLinearColorTable(GDHandle device);
  75. Creates a default table for use when gdType==directType.
  76.  
  77. OSErr GDPrintGammaTable(FILE *o,GDHandle device);
  78.  
  79. OSErr GDRestoreDeviceClut(GDHandle device);
  80. Nominally equivalent to Apple's RestoreDeviceClut(), which is only available
  81. since System 6.05. However, I find that Apple's routine sometimes does nothing,
  82. whereas this routine always works. Passing a NULL argument causes restoration of
  83. cluts of all video devices.
  84.  
  85. OSErr GDSaveGamma(GDHandle device);
  86. OSErr GDRestoreGamma(GDHandle device);
  87. Use an internal cache to save and restore the device's gamma-correction table. Call
  88. GDRestoreGamma before GDRestoreDeviceClut.
  89.  
  90. OSErr GDSetEntries(GDHandle device,short start,short count,ColorSpec *table);
  91. Does a cscSetEntries call to the video card's driver, loading any
  92. number of clut entries with arbitrary rgb triplets. (Note that the driver will
  93. transform your rgb triplets via the gamma table before loading them into the
  94. clut; so call GDUncorrectedGamma first.) "device" specifies which video device's
  95. clut you want to load. "start" is either in the range 0 to clutSize-1,
  96. indicating which clut entry to load first (in "sequence mode"), or is -1
  97. (requesting "index mode"). "count" is the number of entries to be modified,
  98. minus 1. "table" is a ColorSpec array (not a ColorTable) containing the rgb
  99. triplets that you want to load into the clut. In sequence mode "start" must be
  100. in the range 0 to clutSize-1, the i-th element of table corresponds to the
  101. i+start entry in the clut, and the "value" field of each element of table is
  102. ignored. In index mode "start" must be -1, and the "value" field of each element
  103. of table indicates which clut entry to load it into. The arguments start, count,
  104. and table are the same as for the Color Manager call SetEntries(), documented in
  105. Inside Macintosh V-143. (Most drivers wait for blanking before modifying the
  106. clut. For a full discussion, read the VideoToolbox "Video synch" file.) You may
  107. also want to look at the file SetEntriesQuickly.c, which provides the
  108. functionality of GDSetEntries and GDDirectSetEntries, but bypasses the video
  109. driver to access the hardware directly.
  110.  
  111. OSErr GDSetEntriesByType(GDHandle device,short start,short count,ColorSpec *table);
  112. Checks the (**device).gdType field and calls cscSetEntries, cscDirectSetEntries,
  113. or nothing, as appropriate.
  114.  
  115. OSErr GDSetEntriesByTypeHighPriority(GDHandle device,short start,short count
  116.     ,ColorSpec *table);
  117. Calls GDSetEntriesByType() while the processor priority has been temporarily 
  118. raised to 7.
  119.  
  120. OSErr GDSetGamma(GDHandle device, GammaTbl *gamma);
  121. Calls cscSetGamma. Loads a Gamma table into the specified video device. The
  122. video driver will make a copy of your table. You can discard your table after
  123. making this call. Note that the video driver only uses the gamma table when
  124. performing SetEntries, i.e. when actually loading the clut. The structure of the
  125. gamma table is (finally!) documented in Designing Cards and Drivers, 3rd
  126. edition, pages 215-216. Beware of a discrepancy between the documentation and
  127. the definition in QuickDraw.h: gFormulaData is described as a byte array in the
  128. text, but is declared as a short array in the QuickDraw.h header file. NOTE: a
  129. few video drivers (Radius PowerView and SuperMac ColorCard) do not support gamma
  130. tables. The SuperMac ColorCard is well behaved, giving the appropriate error
  131. code, returned by GDSetGamma and GDGetGamma. The Radius PowerView reports no
  132. error yet ignores the GDSetGamma call and returns a table full of zeroes in
  133. response to GDGetGamma. See NOTE from Tom Busey below. However, if all you want
  134. to do is call GDUncorrectedGamma, then these limitations won't affect you,
  135. because the drivers that lack gamma tables always give you precisely the
  136. behaviour that one requests by calling GDUncorrectedGamma.
  137.  
  138. OSErr GDSetPageDrawn(GDHandle device,short page);
  139. Choose which page of video memory will be used by future drawing operations. 
  140. Untested.
  141.  
  142. OSErr GDSetPageShown(GDHandle device,short page);
  143. Choose which page of video memory we see. Untested.
  144.  
  145. OSErr GDUncorrectedGamma(GDHandle device);
  146. Asks GDSetGamma to load a linear gamma table, i.e. no correction. (The gamma
  147. correction implemented by table-lookup in the video driver is too crude for
  148. experiments that want accurate luminance control.)
  149.  
  150. int GDVersion(GDHandle device)
  151. Returns the version number of the driver. From the first word-aligned word after
  152. the name string. This is quick.
  153.  
  154. OSErr GDGetNextResolution()
  155. Implements cscGetNextResolution.
  156.  
  157. LESS-USEFUL (LOW LEVEL) ROUTINES:
  158.  
  159. OSErr GDControl(int refNum,int csCode,Ptr csParamPtr)
  160. Uses low-level PBControl() call to implement a "Control()" call that works! 
  161. I don't know why this wasn't discussed in Apple Tech Note 262.
  162.  
  163. OSErr GDDirectSetEntries(GDHandle device,short start,short count,ColorSpec *table);
  164. Calls cscDirectSetEntries. If your pixel depth is >8 then the cscSetEntries call is
  165. disabled, and you must use this instead of GDSetEntries().
  166.  
  167. VideoDriver *GDDriverAddress(GDHandle device);
  168. Returns a pointer to the driver, whether in ROM or RAM. Neither this prototype
  169. nor the definition of the VideoDriver structure are included in VideoToolbox.h.
  170.  
  171. OSErr GDGetDefaultMode(GDHandle device,short *modePtr)
  172. Calls cscGetDefaultMode. It tells you what the default mode is. I'm not sure
  173. what this means.
  174.  
  175. OSErr GDGetGray(GDHandle device,Boolean *flagPtr);
  176. Calls cscGetGray. Get gray flag. 0 for color. 1 if all colors mapped to
  177. luminance-equivalent gray tones.
  178.  
  179. OSErr GDGetInterrupt(GDHandle device,Boolean *flagPtr);
  180. Calls cscGetInterrupt. Get flag. 1 if VBL interrupts of this card are enabled. 0
  181. if disabled.
  182.  
  183. OSErr GDGetMode(GDHandle device,short *modePtr,short *pagePtr,Ptr *baseAddrPtr);
  184. Calls cscGetMode. It tells you the current mode, page of video memory, and the
  185. base address of that page.
  186.  
  187. OSErr GDGetPageBase(GDHandle device,short page,Ptr *baseAddrPtr);
  188. Calls cscGetPageBase. (Called "cscGetBaseAddr" in Designing Cards and Drivers, 3rd
  189. Ed.) You tell it which page of video memory you're interested in (in the current
  190. video mode). It tells you the base address of that page.
  191.  
  192. OSErr GDGrayPage(GDHandle device,short page);
  193. Calls cscGrayPage. (Called "cscGrayScreen" in Designing Cards and Drivers, 3rd
  194. Ed.) Fills the specified page with gray, i.e. the dithered desktop pattern. I'm
  195. not aware of any particular advantage in using this instead of FillRect().
  196. Designing Cards and Drivers, 3rd Edition, Chapter 9, says that for direct
  197. devices, i.e. >8 bit pixels, the driver will also load a linear,
  198. gamma-corrected, gray color table.
  199.  
  200. OSErr GDReset(GDHandle device, short *modePtr, short *pagePtr, Ptr *baseAddrPtr);
  201. Calls cscReset. Initialize the video card to its startup state, usually 1 bit
  202. per pixel. Returns the parameters of that state.
  203.  
  204. OSErr GDSetDefaultMode(GDHandle device,short mode);
  205. Calls cscSetDefault. Supposedly, you tell it what mode you want to start up with
  206. when you reboot. (I've never been able to get this to work. No error and no
  207. effect. Perhaps I've misunderstood its purpose.)
  208.  
  209. OSErr GDSetGray(GDHandle device,Boolean flag);
  210. Calls cscSetGray. Set gray flag. 0 for color. 1 if all colors mapped to
  211. luminance-equivalent gray tones.
  212.  
  213. OSErr GDSetInterrupt(GDHandle device,Boolean flag);
  214. Calls cscSetInterrupt. Set flag to 1 to enable VBL interrupts of this card, or 0
  215. to disable.
  216.  
  217. OSErr GDSetMode(GDHandle device,short mode,short page,Ptr *baseAddrPtr);
  218. Calls cscSetMode. You tell it what mode and video page you want. It sets 'em and
  219. returns the base address of that page in video memory. Also, because Apple said
  220. so, the video driver sets the entire clut to 50% gray. Note that this changes
  221. things behind QuickDraw's back. For most applications life will be simpler if
  222. you overtly ask QuickDraw to take charge by calling Apple's SetDepth() instead
  223. of GDSetMode(). WARNING: Apple now considers the mode numbers merely ordinal.
  224. E.g. on the 8•24 video card the 32-bit mode has mode number 0x84, not 0x85 as
  225. you might have expected on the basis of old Apple documentation and other Apple
  226. video cards.
  227.  
  228. OSErr GDStatus(int refNum,int csCode,Ptr csParamPtr)
  229. Uses low-level PBStatus() call to implement a "Status()" call that works! The
  230. need for this is explained in Apple Tech Note 262, which was issued in response
  231. to my bug report in summer of '89.
  232.  
  233. PatchMacIIciVideoDriver();
  234. Fixes a crashing bug in the Mac IIci built-in video driver's implementation of
  235. cscGetEntries. The patch persists until reboot. It is unlikely that you will need
  236. to call this explicitly, PatchMacIIciVideoDriver() is automatically invoked the
  237. first time GDGetEntries is called. The Mac IIci built-in video driver
  238. (.Display_Video_Apple_RBV1 driver, version 0) has a bug that causes it to crash
  239. if you try to do a GetEntries Status request. PatchMacIIciVideoDriver() finds and
  240. patches the copy of the buggy driver residing in memory. (If the driver is
  241. ROM-based it first moves it to RAM, and then patches that.) Only two instructions
  242. are modified, to save & restore more registers. This fix persists only until the
  243. next reboot. If the patch is successfully applied the version number is increased
  244. by 100.
  245.  
  246. NOTES:
  247.  
  248. Several bugs in version 2 (in System ≤6.03) of the video driver for Apple's
  249. "Toby Frame Buffer" video card that affected use of the GetGamma call were
  250. fixed in version 3 (in System 6.04), apparently in response to my bug report to
  251. Apple.
  252.  
  253. The control/status-call parameter in a GDControl or GDStatus call specifies what
  254. you want done. See Designing Cards and Drivers, 3rd Edition, Chapter 9. (A few
  255. new calls are documented in the Display Device Driver Guide Developer Note.)
  256.  Note that sometime around 1990 Apple renamed some of the Control and Status
  257. calls, giving them names that better reflect their function. I followed suit.
  258. However, Apple neglected to update their book, Designing Cards and Drivers, now
  259. in its 3rd edition. Fortunately, they define both names in their Video.h header
  260. file. To avoid confusion, here are the equivalences. Note that "csc" stands for
  261. "Control and Status Call"
  262. Control call:
  263.  cscGrayPage =  cscGrayScreen = 5
  264. Status calls:
  265.  cscGetPageCnt = cscGetPages = 4
  266.  cscGetPageBase = cscGetBaseAddr = 5
  267.  
  268. Based on:
  269. Inside Macintosh-II (Device Manager)
  270. Designing Cards and Drivers, 3rd Edition, Chapter 9.
  271. Display Device Driver Guide Developer Note on the January '94 Developer CD.
  272. Tech Note 262: "Controlling Status Calls"
  273. "GreyScale Information" from AppleLink "Apple Technical Info"
  274. "Video Configuration ROM Software Specification" also from AppleLink,
  275. in "Developer Tech Support:Macintosh:32 Bit QuickDraw"
  276.  
  277. NOTES:
  278. Tom Busey (busey@indiana.edu) writes: "I'm using an 8-bit SuperMac ColorCard
  279. that a used computer dealer gave me when I ordered a Toby card. I discovered
  280. that the status and control calls for GDUncorrectedGamma return -17 and -18
  281. respectively, which means that the driver doesn't support different gammas.
  282. GDUncorrectedGamma returns an error message, but GDOpenWindow doesn't use the
  283. error message or pass it back to the calling program. I'm wondering if there are
  284. people using GDOpenWindow who think that they are getting a linear gamma but who
  285. are actually getting an error message and not learning about it."
  286.      Tom's facts are right, but he needn't worry. A few video drivers, e.g.
  287. Radius PowerView, and apparently the SuperMac ColorCard, don't implement gamma
  288. tables at all, but the error from GDUncorrectedGamma is probably not a concern.
  289. The real test is to run TimeVideo. TimeVideo does a write-and-read-back test of
  290. the clut of your video card. If that test passes then you can safely conclude
  291. that there's no gamma translation going on. So, as nearly every document in the
  292. VideoToolbox says: run TimeVideo and read the report.
  293.      Here's how gamma tables work. According to the Apple manual (Designing
  294. Cards and Drivers), the values in the rgb triplets that you supply in a
  295. cscSetEntries call to the video driver are first translated via the gamma table
  296. (each r,g, and b component separately) before being loaded into the CLUT
  297. hardware table. Most drivers maintain a gamma table internally (in computer
  298. memory) and allow you to get and set it via the cscGetGamma and cscSetGamma
  299. calls. A few video drivers (Radius PowerView, SuperMac ColorCard) don't support
  300. gamma tables. They load your rgb values directly into the CLUT, without
  301. translation. However, for users of the VideoToolbox that's usually fine, since
  302. that's exactly the behavior that we routinely request by calling
  303. GDUncorrectedGamma. Of course, if you want to load a custom gamma table, other
  304. than the identity transformation, then you'll be calling GDSetGamma, and you
  305. should make sure it does not return an error. (Alas, the Radius PowerView driver
  306. more or less ignores the cscSetGamma and cscGetGamma requests--GDGetGamma
  307. returns a table that's all zeroes--but the driver fails to report an error. I
  308. wrote to the Radius programmer a year ago, but they're no longer interested in
  309. working on that product.)
  310.     Patrick Flanagan (flanagan@deakin.edu.au) writes: "Can I be 100% sure, if I
  311. select "Special Gamma", in the Monitors Control Panel and choose "uncorrected
  312. gamma" for a video card, that this is the same as using GDUncorrectedGamma?"
  313. REPLY: That is what I would expect from reading all the relevant documentation.
  314. However, to be 100% certain of anything I would want to check it myself.
  315. TimeVideo calls GDUncorrectedGamma and then confirms that write-then-read tests
  316. of the CLUT return what was written. (Gamma-table translation is only done on
  317. the write, not undone on the read.) Thus TimeVideo will confirm for you that
  318. after calling GDUncorrectedGamma your video card has what Apple calls an
  319. "uncorrected" gamma table. However, TimeVideo does not check what you would get
  320. by merely selecting "uncorrected" gamma in the Monitors Control Panel. It would
  321. be reasonable to assume that you would get the same result since Monitors
  322. interacts with the video driver by the same Control and Status Calls as
  323. GDVideo.c does, so it must use the same cscSetGamma call as is used by
  324. GDUncorrectedGamma.
  325.  
  326. HISTORY:
  327. 9/29/89     dgp    added caution above that successive calls to SetEntries may be on one 
  328.                 frame.
  329. 11/21/89    dgp    corrected mode list: 0x80... as pointed out by Chuck Stein
  330. 11/30/89    dgp    added note above from Don Kelly.
  331.                 Added cautionary note above about GDSetEntries().
  332. 3/1/90        dgp    updated comments.
  333. 3/3/90        dgp    included Video.h instead of defining VDSetEntryRecord and VDPageInfo.
  334. 3/20/90        dgp    made compatible with MPW C.
  335. 3/23/90        dgp    changed char to unsigned char in VDDefModeRec
  336.                 and VDFlagRec to prevent undesirable sign extension.
  337. 4/2/90        dgp    Deleted mode argument from GDGrayScreen().
  338. 7/28/90        dgp Fixed stack overflow in GDGrayScreen, by declaring SysEnvRec static.
  339. 10/20/90    dgp    Apple has renamed the control and status calls, so I followed suit:
  340.                 •GDGetPageBase replaces GDGetBaseAddr
  341.                 •GDReset replaces GDInit
  342.                 •GDGrayPage replace GDGrayScreen
  343.                 •GDGetPageCnt replaces GDGetPages
  344. 2/12/91        dgp Discovered that the old bug in GDGrayPage is still present in System
  345.                 6.05, so I removed the conditional around the bug fix. TestGDVideo
  346.                 now works with: Mac II Video Card, Mac II Display Card (4•8), 
  347.                 Mac IIci Built-in Video, TrueVision NuVista, Mac IIsi Built-in Video.
  348. 7/22/91        dgp    Changed definition of csGTable from GammaTblPtr to Ptr, 
  349.                 to conform with MPW C.
  350. 8/24/91        dgp    Made compatible with THINK C 5.0.
  351. 10/22/91    dgp    With help from Bart Farell, converted all functions headers to
  352.                 Standard C style.
  353. 8/26/92        dgp    added a few miscellaneous comments
  354.                 In all routines, *baseAddrPtr is now set only if baseAddrPtr is not NULL.
  355. 10/10/92    dgp    Added GDRestoreDeviceClut(). Removed obsolete support for THINK C 4.
  356. 11/30/92    dgp corrected error in comment documenting values of argument to GDSetGray().
  357.                 Set flag to zero for color,1 for luminance-mapped gray.
  358. 12/9/92        dgp    Enhanced GDRestoreDeviceClut(). Passing a NULL argument now requests
  359.                 application to all devices. I only just learned that Apple's
  360.                 RestoreDeviceClut() behaves in this way.
  361. 12/15/92    dgp Renamed GDRestoreDeviceClut to GDRestoreDeviceClut to be consistent
  362.                 with Apple's capitalization of RestoreDeviceClut.
  363. 12/16/92    dgp Updated comments to be consistent with 3rd edition of Designing Cards
  364.                 and Drivers. •Renamed myGDHandle to "device", which is easier to read.
  365.                 Renamed GDLinearGamma to GDUncorrectedGamma, and generalized it
  366.                 to work with any size DAC. For compatibility with old programs
  367.                 VideoToolbox.h now has a #define statement making GDLinearGamma
  368.                 an alias for GDUncorrectedGamma.
  369. 12/30/92    dgp Updated some of the comments. Eliminated Files.h.
  370. 12/30/92    dgp Use GDClutSize() to determine clut size.
  371. 1/4/93        dgp In GDClutSize, check for fixedType.
  372. 1/5/93        dgp In GDClutSize, only set last clut entry.
  373.                 Added PatchMacIIciVideoDriver() to the end of this file, and 
  374.                 automatically invoke it the first time GDGetEntries is called.
  375. 1/6/93        dgp    Cleaned up GDClutSize. It now seems to work correctly in the direct modes.
  376. 1/18/93    dgp    Spruced up the documentation.
  377.             •Added all the code formerly in GDIdentify.c, but omitted the obsolete 
  378.             function GDIdentify(), which simply printed GDName() and GDVersion.
  379.             •Enhanced GDGetEntries() to avoid calling drivers that are known
  380.             to crash, returning a statusErr instead.
  381.             •Recoded PatchMacIIciVideoDriver() so as not to call GetScreenDevice.c.
  382. 2/1/93    dgp    Fixed endless loop in PatchMacIIciVideoDriver. Enhanced to deal with
  383.             ROM-based drivers as well.
  384. 2/5/93    dgp    Expanded the documentation of GDSetEntries above, and supplied sample
  385.             code showing how to load the clut.
  386. 2/7/93    dgp Fixed endless loop in PatchMacIIciVideoDriver.
  387. 2/20/93    dgp    Fixed bug in GDUncorrectedGamma() that was causing TestCluts to fail
  388.             for video devices that have nonstandard gamma tables. 
  389. 3/18/93    dgp    Fixed divide by zero error in GDClutSize.
  390. 4/6/93    dgp    GDGetPageCnt() now sets *pagePtr argument only if no error occurs.
  391.             Deleted GDModeName(). Removed assumption, in all routines, that there
  392.             is any particular correspondence between the video mode number and
  393.             the pixel size. Added two new routines, GDPixelSize and GDType,
  394.             that return the pixelSize and gdType (i.e. fixedType, clutType, or 
  395.             directType) of the device. Completely rewrote GDClutSize.
  396. 4/16/93    dgp    Streamlined GDClutSize() to make it fast enough for routine use.
  397. 4/19/93    dgp    Added GDNewLinearColorTable.
  398. 4/25/93    dgp    Made CntrlParam automatic instead of static.
  399. 4/25/93    dgp    Added GDColors(device) and GDPrintGammaTable(). Alphabetized the lists
  400.             of functions in the documentation above.
  401. 5/11/93    dgp    Changed GDPrintGammaTable() to accept a simple file pointer instead of
  402.             an array of two file pointers.
  403. 7/7/93    dgp enhanced GDDacSize() to return 8 unless the gamma table is present and
  404.             reasonable.
  405. 7/29/94    dgp    added GDNameStr().
  406. 9/5/94 dgp removed assumption in printf's that int==short.
  407. 10/25/94 dgp check for missing driver, (*device)->gdRefNum==0, and treat that case
  408.             just like  device==NULL. Devices created by NewGWorld have no driver.
  409. 12/29/94 dgp added GDGetDisplayMode(), calls cscGetCurMode, based on Apple's new
  410.             Display Device Driver Guide Developer Note on the January '94 Developer CD.
  411. 1/15/94 dgp GDPixelSize if supplied with a merely device record, with no associated 
  412.             device driver, then we just return (**(**device).gdPMap).pixelSize
  413. 3/22/95 dgp Added .Display_Video_Apple_DOMEMax to the list of drivers that don't
  414.             support cscGetEntries. Crash reported by Greg Jackson.
  415. 4/6/95 dgp Changed GDUncorrectedGamma() to pass a NULL gamma table pointer instead of
  416.             a linear gamma table, in the hopes that this might work even with the
  417.             few video drivers that don't fully support cscSetGamma.
  418. */
  419.  
  420. #include "VideoToolbox.h"
  421. #include <assert.h>
  422. #include <ROMDefs.h>
  423. //#include <Displays.h>
  424. #define dRAMBased 0x0040
  425.  
  426. #if !UNIVERSAL_HEADERS
  427.     /* these declarations appear in the latest Video.h */
  428.     struct VDSwitchInfoRec{
  429.         unsigned short csMode;
  430.         unsigned long csData;
  431.         unsigned short csPage;
  432.         Ptr csBaseAddr;
  433.         unsigned long csReserved;
  434.     };
  435.     typedef struct VDSwitchInfoRec VDSwitchInfoRec;
  436.     enum{cscGetCurMode=10};
  437.     enum{cscGetNextResolution=17};
  438.     typedef unsigned long DisplayModeID;
  439.     typedef unsigned short DepthMode;
  440.     struct VDResolutionInfoRec {
  441.         DisplayModeID                    csPreviousDisplayModeID;    /* ID of the previous resolution in a chain */
  442.         DisplayModeID                    csDisplayModeID;            /* ID of the next resolution */
  443.         unsigned long                    csHorizontalPixels;            /* # of pixels in a horizontal line */
  444.         unsigned long                    csVerticalLines;            /* # of lines in a screen */
  445.         Fixed                            csRefreshRate;                /* Vertical Refresh Rate in Hz */
  446.         DepthMode                        csMaxDepthMode;                /* 0x80-based number representing max bit depth */
  447.         unsigned long                    csReserved;                    /* Reserved */
  448.         unsigned long                    csReserved1;                /* Reserved */
  449.     };
  450.     typedef struct VDResolutionInfoRec VDResolutionInfoRec;
  451.     typedef VDResolutionInfoRec *VDResolutionInfoPtr;
  452. #endif
  453.  
  454. typedef struct VDFlagRec {
  455.     unsigned char flag;
  456.     char pad;
  457. } VDFlagRec;
  458.  
  459. typedef struct VDDefModeRec{
  460.     unsigned char spID;
  461.     char pad;
  462. } VDDefModeRec;
  463.  
  464. typedef struct {
  465.     short flags;
  466.     short blanks[3];
  467.     short open;
  468.     short prime;
  469.     short control;
  470.     short status;
  471.     short close;
  472.     Str255 name;
  473. } VideoDriver;
  474. VideoDriver *GDDriverAddress(GDHandle device);
  475.  
  476. typedef struct {
  477.     short csCode;        // control code
  478.     short length;        // total parameter block bytes
  479.     char param[];        // control call data
  480. } ScrnCtl;
  481.  
  482. typedef struct {
  483.     short spDrvrHw;        // Slot Manager ID
  484.     short slot;            // Number of slot
  485.     long dCtlDevBase;    // Start of device's address space
  486.     short mode;            // screen characteristics
  487.     short flagMask;        // Which flag bits are used
  488.     short flags;        // device state: bit 0 = 0 = mono; bit 0 = 1 = color;
  489.                         // bit 11 =  1 = startup device; bit 15 = 1 = active
  490.     short colorTable;    // 'clut' id, default = -1
  491.     short gammaTable;    // Selects color intensity, default (MacII) = -1
  492.     Rect globalRect;    // global rectangle, main device topLeft = 0,0
  493.     short ctlCount;        // total control calls
  494.     ScrnCtl ctl;
  495. } Scrn;
  496.  
  497. typedef struct {
  498.     short scrnCount;    // Total devices
  499.     Scrn scrn;
  500. } Scrns;                // 'scrn' resource
  501.  
  502. Scrn **GDGetScrn(GDHandle device);
  503.  
  504. OSErr GDGetNextResolution(GDHandle device,unsigned long previousDisplayModeID
  505.     ,unsigned long *displayModeIDPtr,unsigned long *horizontalPixelsPtr
  506.     ,unsigned long *verticalLinesPtr,Fixed *refreshRatePtr
  507.     ,unsigned short *maxDepthModePtr);
  508.  
  509. OSErr GDGetDisplayMode(GDHandle device,unsigned long *displayModeIDPtr
  510.     ,unsigned short *modePtr,unsigned short *pagePtr,Ptr *baseAddrPtr)
  511. /*
  512. It tells you the current display mode, etc., but only if the video driver 
  513. supports the Display Manager.
  514. */
  515. {
  516.     VDSwitchInfoRec vdSwitchInfo;
  517.     int error;
  518.  
  519.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  520.     error=GDStatus((*device)->gdRefNum,cscGetCurMode,(Ptr) &vdSwitchInfo);
  521.     if(displayModeIDPtr!=NULL) *displayModeIDPtr=vdSwitchInfo.csData;
  522.     if(modePtr!=NULL) *modePtr=vdSwitchInfo.csMode;
  523.     if(pagePtr!=NULL) *pagePtr=vdSwitchInfo.csPage;
  524.     if(baseAddrPtr!=NULL) *baseAddrPtr=vdSwitchInfo.csBaseAddr;
  525.     return error;
  526. }
  527.  
  528. OSErr GDGetNextResolution(GDHandle device,unsigned long previousDisplayModeID
  529.     ,unsigned long *displayModeIDPtr,unsigned long *horizontalPixelsPtr
  530.     ,unsigned long *verticalLinesPtr,Fixed *refreshRatePtr
  531.     ,unsigned short *maxDepthModePtr)
  532. /*
  533. Tells you the next available displayModeID, after previousDisplayModeID.
  534. This is a new call, introduced for PCI video drivers.
  535. */
  536. {
  537.     VDResolutionInfoRec    vdSwitchInfo;
  538.     int error;
  539.  
  540.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  541.     vdSwitchInfo.csPreviousDisplayModeID=previousDisplayModeID;
  542.     error=GDStatus((*device)->gdRefNum,cscGetNextResolution,(Ptr) &vdSwitchInfo);
  543.     if(displayModeIDPtr!=NULL) *displayModeIDPtr=vdSwitchInfo.csDisplayModeID;
  544.     if(horizontalPixelsPtr!=NULL) *horizontalPixelsPtr=vdSwitchInfo.csHorizontalPixels;
  545.     if(verticalLinesPtr!=NULL) *verticalLinesPtr=vdSwitchInfo.csVerticalLines;
  546.     if(refreshRatePtr!=NULL) *refreshRatePtr=vdSwitchInfo.csRefreshRate;
  547.     if(maxDepthModePtr!=NULL) *maxDepthModePtr=vdSwitchInfo.csMaxDepthMode;
  548.     return error;
  549. }
  550.  
  551. OSErr GDSetPageDrawn(GDHandle device,short page)
  552. // Select a page of video memory to draw into.
  553. // Untested.
  554. {
  555.     int error;
  556.     short flags;
  557.     Ptr baseAddr;
  558.     static long qD=-1;
  559.  
  560.     if(qD==-1)Gestalt(gestaltQuickdrawVersion,&qD);
  561.     error=GDGetPageBase(device,page,&baseAddr);
  562.     if(!error){
  563.         if(qD>=gestalt32BitQD){
  564.             flags=GetPixelsState((**device).gdPMap);
  565.             LockPixels((**device).gdPMap);
  566.         }
  567.         (**(**device).gdPMap).baseAddr=baseAddr;
  568.         if(qD>=gestalt32BitQD){
  569.             GDeviceChanged(device);
  570.             SetPixelsState((**device).gdPMap,flags);
  571.         }
  572.     }
  573.     return error;
  574. }
  575.  
  576. OSErr GDSetPageShown(GDHandle device,short page)
  577. // Select a page of video memory for display.
  578. // Untested.
  579. {
  580.     int error;
  581.     short mode;
  582.  
  583.     error=GDGetMode(device,&mode,NULL,NULL);
  584.     if(error)return error;
  585.     return GDSetMode(device,mode,page,NULL);
  586. }
  587.  
  588. short GDType(GDHandle device)
  589. // Returns what would normally be in (**device).gdType, for occasions when
  590. // the GDevice record might be invalid because you called GDSetMode().
  591. {
  592.     int error;
  593.     static ColorSpec white={255,0xffff,0xffff,0xffff},black={0,0,0,0};
  594.  
  595.     error=GDSetEntries(device,0,0,&white);
  596.     if(!error)return clutType;
  597.     error=GDDirectSetEntries(device,0,0,&black);
  598.     if(!error)return directType;
  599.     return fixedType;
  600. }
  601.  
  602. short GDPixelSize(GDHandle device)
  603. // Returns what would normally be in (**(**device).gdPMap).pixelSize, for occasions
  604. // when the GDevice record might be invalid because you called GDSetMode().
  605. // Exception: if this is merely a device record, with no associated device driver,
  606. // then we just return (**(**device).gdPMap).pixelSize
  607. {
  608.     int error;
  609.     short mode;
  610.  
  611.     if((**device).gdRefNum==0)return (**(**device).gdPMap).pixelSize;
  612.     error=GDGetMode(device,&mode,NULL,NULL);
  613.     return GDModePixelSize(device,mode);
  614. }
  615.  
  616. short GDModePixelSize(GDHandle device,short mode)
  617. // Returns the pixelSize associated with a given video mode.
  618. // If you've changed the mode by calling GDSetMode and you're running a System 
  619. // older than 6.0.5 the answer may may be wrong for some of the newer video cards,
  620. // because they have ideosynchratic associations of video mode and pixel size.
  621. {
  622.     short j;
  623.     long version;
  624.  
  625.     if(mode==(**device).gdMode)return (**(**device).gdPMap).pixelSize;
  626.     Gestalt(gestaltSystemVersion,&version);
  627.     if(version>=0x605){            // Need new Palette Manager for reliable answer.
  628.         for(j=5;j>=0;j--)if(mode==HasDepth(device,1<<j,0,0))return 1<<j;
  629.     } else return 1<<(mode&7);    // Unreliable.
  630.     return 0;
  631. }
  632.  
  633. Boolean GDHasMode(GDHandle device,short mode,short *pixelSizePtr,short *pagesPtr);
  634.  
  635. Boolean GDHasMode(GDHandle device,short mode,short *pixelSizePtr,short *pagesPtr)
  636. // Returns 0 if no such mode, returns 1 if mode is available.
  637. // If pixelSizePtr is not NULL, then sets *pixelSizePtr to pixelSize or -1 if unknown.
  638. // If pagesPtr is not NULL, then sets *pagesPtr to pages.
  639. {
  640.     short pixelSize,i,hasDepthWorks,pages;
  641.     int error;
  642.     long system;
  643.     
  644.     Gestalt(gestaltSystemVersion,&system);
  645.     // On Mac IIci, Sys 6.07, HasDepth returns "mode" of 0x100 at all legal depths.
  646.     hasDepthWorks= system>=0x605     // New Palette Manager.
  647.         && HasDepth(device,(**(**device).gdPMap).pixelSize,0,0)==(**device).gdMode;
  648.     if(hasDepthWorks){
  649.         for(i=0;i<6;i++){
  650.             pixelSize=1<<i;
  651.             if(mode!=HasDepth(device,pixelSize,0,0))continue;
  652.             if(pixelSizePtr!=NULL)*pixelSizePtr=pixelSize;
  653.             if(pagesPtr!=NULL){
  654.                 error=GDGetPageCnt(device,mode,&pages);
  655.                 if(error)pages=1;
  656.                 *pagesPtr=pages;
  657.             }
  658.             return 1;
  659.         }
  660.         return 0;
  661.     }else{
  662.         // If HasDepth doesn't work properly then we can still find out whether the
  663.         // mode is available by asking the video driver for a page count, but
  664.         // I don't know of any discreet way to find out the pixelSize.
  665.         // Calling SetDepth would work, but that would irritate the user who has to
  666.         // watch and wait. 
  667.         error=GDGetPageCnt(device,mode,&pages);
  668.         if(error)pages=0;
  669.         if(pagesPtr!=NULL)*pagesPtr=pages;
  670.         if(mode==(**device).gdMode)pixelSize=(**(**device).gdPMap).pixelSize;
  671.         else pixelSize=-1;        // Unknown.
  672.         if(pixelSizePtr!=NULL)*pixelSizePtr=pixelSize;
  673.         return (pages>0);
  674.     }
  675. }
  676.  
  677. short gdClutSizeTable[33]={0,1<<1,1<<2,0,1<<4,0,0,0,1<<8,0,0,0,0,0,0,0,1<<5
  678. ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1<<8};
  679.  
  680. long GDColors(GDHandle device)
  681. // Returns the number of colors, in the current mode.
  682. {
  683.     long colors=0;
  684.     short pixelSize;
  685.     
  686.     if(device==NULL)return 2;    // for compatibility with 1-bit QuickDraw
  687.     pixelSize=(**(**device).gdPMap).pixelSize;
  688.     if(pixelSize>=1 && pixelSize<=8)colors=1<<pixelSize;
  689.     if(pixelSize==16)colors=1L<<15;
  690.     if(pixelSize==32)colors=1L<<24;
  691.     return colors;
  692. }
  693.  
  694. short GDClutSize(GDHandle device)
  695. // Returns the number of entries in the clut, in the current mode.
  696. {
  697.     short clutSize;
  698.     
  699.     // Method 1. Estimate clut size from pixel size.
  700.     clutSize=gdClutSizeTable[(**(**device).gdPMap).pixelSize];
  701.  
  702.     #if 0
  703.     // Method 2. Measure the clut's size by trying to load it.
  704.     if(GDType(device)==directType){
  705.         int error,i;
  706.         static const ColorSpec white={255,0xffff,0xffff,0xffff},black={0,0,0,0};
  707.         ColorSpec *table;
  708.         for(clutSize=256;clutSize>1;clutSize>>=1){
  709.             table=GDNewLinearColorTable(device);
  710.             if(table==NULL)PrintfExit("GDClutSize: out of memory.\n");
  711.             error=GDDirectSetEntries(device,0,clutSize-1,table);
  712.             DisposePtr((Ptr)table);
  713.             if(!error)break;
  714.         }
  715.     }
  716.     #endif
  717.     
  718.     return clutSize;
  719. }
  720.  
  721. short GDDacSize(GDHandle device)
  722. // Figures out how many bits in the video dac. Answers for each device are cached.
  723. {
  724.     short dacSize,i;
  725.     static short dacSizeCache[MAX_SCREENS];
  726.     static GDHandle deviceCache[MAX_SCREENS];
  727.     int error;
  728.     GammaTbl *gammaTblPtr=NULL;
  729.  
  730.     for(i=0;i<MAX_SCREENS;i++)if(device==deviceCache[i])return dacSizeCache[i];
  731.     error=GDGetGamma(device,&gammaTblPtr);        // Takes 200 µs.
  732.     if(error || gammaTblPtr==NULL || gammaTblPtr->gDataWidth==0)dacSize=8;                            // Oops. Take a guess.
  733.     else dacSize=gammaTblPtr->gDataWidth;
  734.     for(i=0;i<MAX_SCREENS;i++)if(NULL==deviceCache[i]){
  735.         deviceCache[i]=device;
  736.         dacSizeCache[i]=dacSize;
  737.         break;
  738.     }
  739.     return dacSize;
  740. }
  741.  
  742. ColorSpec *GDNewLinearColorTable(GDHandle device)
  743. // Creates a default table for use when gdType==directType.
  744. {
  745.     short clutSize,i;
  746.     ColorSpec *table,*linearTable;
  747.     
  748.     clutSize=GDClutSize(device);
  749.     table=linearTable=(ColorSpec *)NewPtr(clutSize*sizeof(linearTable[0]));
  750.     if(linearTable!=NULL)for(i=0;i<clutSize;i++){
  751.         table->rgb.red=table->rgb.green=table->rgb.blue
  752.             =(0xffffL*i+clutSize/2)/(clutSize-1);
  753.         table++;
  754.     }
  755.     return linearTable;
  756. }
  757.  
  758. /*
  759. Nominally equivalent to Apple's RestoreDeviceClut(), which is only available
  760. since System 6.05. However, I find that Apple's routine sometimes does nothing,
  761. whereas this routine always works. Passing a NULL argument causes restoration of
  762. cluts of all video devices.
  763. */
  764. OSErr GDRestoreDeviceClut(GDHandle device)
  765. {
  766.     int error,lastError;
  767.     short count;
  768.  
  769.     // If NULL, then recursively call ourselves for each device.
  770.     if(device==NULL){
  771.         lastError=0;
  772.         device=GetDeviceList();
  773.         while(device!=NULL) {
  774.             if(TestDeviceAttribute(device,screenDevice))
  775.                 error=GDRestoreDeviceClut(device);
  776.             if(error)lastError=error;
  777.             device=GetNextDevice(device);
  778.         }
  779.         return lastError;
  780.     }
  781.     if(GDType(device)!=directType){
  782.         count=(**(**(**device).gdPMap).pmTable).ctSize;
  783.         error=GDSetEntries(device,0,count
  784.             ,((**(**(**device).gdPMap).pmTable)).ctTable);
  785.     } else error=GDSetGamma(device,NULL);
  786.     return error;
  787. }
  788.  
  789. GammaTbl **savedGammaTable[MAX_SCREENS];
  790.  
  791. OSErr GDSaveGamma(GDHandle device)
  792. {
  793.     GammaTbl *gamma;
  794.     int error;
  795.     long size;
  796.     int i;
  797.  
  798.     if(device==NULL || (*device)->gdType==fixedType)return 0;
  799.     i=GetScreenIndex(device);
  800.     if(i>=MAX_SCREENS)return 1;
  801.      error=GDGetGamma(device,&gamma);
  802.     if(error)return error;
  803.     size=gamma->gChanCnt*gamma->gDataCnt;
  804.     if(gamma->gDataWidth>8)size*=2;
  805.     size+=sizeof(GammaTbl)+gamma->gFormulaSize;
  806.     if(savedGammaTable[i]!=NULL){
  807.         DisposeHandle((Handle)savedGammaTable[i]);
  808.         savedGammaTable[i]=NULL;
  809.     }
  810.     error=PtrToHand(gamma,(Handle *)&savedGammaTable[i],size);
  811.     return error;
  812. }
  813.  
  814. OSErr GDRestoreGamma(GDHandle device)
  815. {
  816.     int i,error;
  817.     
  818.     if((*device)->gdType==fixedType)return 0;
  819.     i=GetScreenIndex(device);
  820.     if(i>=MAX_SCREENS || savedGammaTable[i]==NULL)return 1;
  821.     error=GDSetGamma(device,*savedGammaTable[i]);
  822.     if(error)return error;
  823.     DisposeHandle((Handle)savedGammaTable[i]);
  824.     savedGammaTable[i]=NULL;
  825.     return 0;
  826. }    
  827.  
  828. OSErr GDGetDefaultGamma(GDHandle device,GammaTbl **gammaTbl)
  829. // Looks for a default gamma table in both places that Apple says to look,
  830. // but usually comes up empty handed.
  831. {
  832.     int error,i,slot;
  833.     Scrn **scrn;
  834.     GammaTbl **gammaHandle,*gamma;
  835.     SpBlock spBlock;
  836.     Ptr ptr;
  837.  
  838.     gammaHandle=NULL;
  839.     if(CountResources('gama')>0){// Any 'gama' resources available in System file?
  840.         // Check to see if 'scrn' resource in System file specifies a 'gama' resource.
  841.         scrn=GDGetScrn(device);
  842.         if(scrn!=NULL && (**scrn).gammaTable!=-1)
  843.             gammaHandle=(GammaTbl **)GetResource('gama',(**scrn).gammaTable);
  844.         DisposeHandle((Handle)scrn);
  845.     }
  846.     if(gammaHandle!=NULL){
  847.         // Got gamma table from 'gama' resource.
  848.         gamma=(GammaTbl *)NewPtr(GetHandleSize((Handle)gammaHandle));
  849.         if(gamma==NULL)return MemError();
  850.         BlockMove(*gammaHandle,gamma,GetHandleSize((Handle)gammaHandle));
  851.         DisposeHandle((Handle)gammaHandle);
  852.     }else{
  853.         // Try to get this device's default gamma table from Slot Manager.
  854.         spBlock.spSlot=slot=GetDeviceSlot(device);
  855.         spBlock.spID=0;
  856.         spBlock.spExtDev=0;
  857.         spBlock.spTBMask=3;            // match only spCategory and spCType
  858.         spBlock.spCategory=catDisplay;
  859.         spBlock.spCType=typeVideo;    // this might be too restrictive, excludes LCD
  860.         do{
  861.             error=SNextTypeSRsrc(&spBlock);
  862.             if(error)return error;
  863.         }while(spBlock.spSlot!=slot || spBlock.spRefNum!=(**device).gdRefNum);
  864.         
  865.         if(0){
  866.             // Print sResource name
  867.             spBlock.spID=sRsrcName;
  868.             error=SGetCString(&spBlock);
  869.             printf("Slot resource “%s”\n",spBlock.spResult);
  870.             if(error)return error;
  871.             DisposePtr((Ptr)spBlock.spResult);
  872.         }
  873.         
  874.         // Look for gamma directory. Unfortunately many video devices don't have one.
  875.         spBlock.spID=sGammaDir;
  876.         error=SFindStruct(&spBlock);
  877.         if(error)return error;
  878.         
  879.         // Retrieve default gamma table
  880.         spBlock.spID=0x80;
  881.         error=SGetBlock(&spBlock);
  882.         if(error)return error;
  883.         gamma=(GammaTbl *)spBlock.spResult;
  884.         ptr=(Ptr)spBlock.spResult+6;
  885.         if(0)printf("Gamma table “%s”, %ld bytes\n",ptr,GetPtrSize((Ptr)gamma));
  886.         ptr+=strlen(ptr)+1;                // table is just past string
  887.         ptr=(Ptr)((long)(ptr+1)&~1L);    // round up to even address
  888.         i=ptr-(Ptr)gamma;
  889.         BlockMove(ptr,(Ptr)gamma,GetPtrSize((Ptr)gamma)-i);
  890.         SetPtrSize((Ptr)gamma,GetPtrSize((Ptr)gamma)-i);
  891.     }
  892.     *gammaTbl=gamma;
  893.     return 0;
  894. }
  895.  
  896. Scrn **GDGetScrn(GDHandle device)
  897. // Returns handle to a copy of the specific scrn resource for this device,
  898. // or NULL if none.
  899. {
  900.     int error=0,i,j;
  901.     Scrns **scrns;
  902.     Scrn *scrn,**scrnHandle;
  903.     ScrnCtl *ctl;
  904.     int scrnCount;
  905.     long size;
  906.  
  907.     scrns=(Scrns **)GetResource('scrn',0);
  908.     if(ResError())return NULL;
  909.     HLockHi((Handle)scrns);
  910.     scrnCount=(**scrns).scrnCount;
  911.     scrn=&(**scrns).scrn;
  912.     for(i=0;i<scrnCount;i++){
  913.         if(0 && scrn->slot==GetDeviceSlot(device)){
  914.             printf("Slot %d,",(int)scrn->slot);
  915.             printf("mode %d,",(int)scrn->mode);
  916.             printf("colorTable %d,",(int)scrn->colorTable);
  917.             printf("gammaTable %d,",(int)scrn->gammaTable);
  918.             printf("%d control calls:",(int)scrn->ctlCount);
  919.         }
  920.         ctl=&scrn->ctl;
  921.         for(j=0;j<scrn->ctlCount;j++){
  922.             if(0 && scrn->slot==GetDeviceSlot(device))printf(" %d",(int)ctl->csCode);
  923.             ctl=(ScrnCtl *)((long)(ctl+1)+ctl->length);
  924.         }
  925.         if(0 && scrn->slot==GetDeviceSlot(device))printf("\n");
  926.         size=(long)ctl-(long)scrn;
  927.         if(scrn->slot==GetDeviceSlot(device))break;
  928.         scrn=(Scrn *)ctl;
  929.     }
  930.     if(i<scrnCount){
  931.         if(error)return NULL;
  932.         scrnHandle=(Scrn **)NewHandle(size);
  933.         BlockMove(scrn,*scrnHandle,size);
  934.     }else scrnHandle=NULL;
  935.     ReleaseResource((Handle)scrns);
  936.     return scrnHandle;
  937. }
  938.  
  939. OSErr GDUncorrectedGamma(GDHandle device)
  940. /*
  941. Loads a linear gamma table into the specified video device, to defeat the
  942. driver's attempt to do gamma correction.
  943.  
  944. According to Designing Cards and Drivers, 3rd edition, passing a NULL
  945. GammaTblPtr instructs the driver to create a linear table. 
  946.  
  947. */
  948. {
  949.     int error,i;
  950.     GammaTbl *gamma=NULL;
  951.     char *gData;
  952.  
  953.     if(0){
  954.         /*
  955.         The the following code first examines the current
  956.         gamma table, and, if it's a plain vanilla table, as described in Designing Cards
  957.         and Drivers, then we write-in the desired linear table. If it's fancy (or if the
  958.         driver doesn't support GDGetGamma) then we pass a NULL pointer, letting the driver
  959.         create the new table. Hopefully this will work with all drivers.
  960.         */
  961.         error=GDGetGamma(device,&gamma);
  962.         if(!error && gamma->gVersion==0 && gamma->gChanCnt==1 && gamma->gDataWidth<=8){
  963.             // Overwrite the standard table
  964.             gData = (char *)&gamma->gFormulaData+gamma->gFormulaSize;
  965.             for(i=0;i<gamma->gDataCnt;i++)gData[i]=i;
  966.         }else{
  967.             // A fancy table implies a new driver, so let it do the work.
  968.             gamma=NULL;
  969.         }
  970.     }
  971.     error=GDSetGamma(device,gamma);
  972.     return error;
  973. }
  974.  
  975. /* KillIO doesn't do anything, so I didn't bother to implement it. */
  976.  
  977. OSErr GDPrintGammaTable(FILE *o,GDHandle device)
  978. {
  979.     unsigned char *byte;
  980.     unsigned short *word;
  981.     int error,i,j,identity;
  982.     GammaTbl *gamma;
  983.     
  984.     if((**device).gdType==fixedType)return statusErr;
  985.     error=GDGetGamma(device,&gamma);
  986.     if(error){
  987.         fprintf(o,"GetGamma: GDGetGamma() error %d\n",error);
  988.         if(error==statusErr)
  989.             fprintf(o,"The video driver doesn't support this call.\n");
  990.         return error;
  991.     }
  992.     byte=(unsigned char *)gamma->gFormulaData+gamma->gFormulaSize;
  993.     word=(unsigned short *)byte;
  994.     identity=1;
  995.     if(gamma->gDataWidth<=8)
  996.         for(i=0;i<gamma->gDataCnt;i++)identity &= (i==byte[i]);
  997.     else
  998.         for(i=0;i<gamma->gDataCnt;i++)identity &= (i==word[i]);
  999.     if(identity){
  1000.         fprintf(o,"Gamma Table: identity transformation\n");
  1001.     }else{
  1002.         fprintf(o,"Gamma Table:\n");
  1003.         fprintf(o,"at 0x%lx,gDataWidth %d,gDataCnt %d,gVersion %d,gType %d,gFormulaSize %d,gChanCnt %d\n"
  1004.             ,gamma,(int)gamma->gDataWidth,(int)gamma->gDataCnt,(int)gamma->gVersion
  1005.             ,(int)gamma->gType,(int)gamma->gFormulaSize,(int)gamma->gChanCnt);
  1006.         for(i=0;i<gamma->gDataCnt;i+=64) {
  1007.             fprintf(o,"%3d: ",i);
  1008.             if(gamma->gDataWidth<=8)
  1009.                 for(j=0;j<16;j++) fprintf(o," %3u",byte[i+j]);
  1010.             else
  1011.                 for(j=0;j<16;j++) fprintf(o," %3u",word[i+j]);
  1012.             fprintf(o,"\n");
  1013.         }
  1014.     }
  1015.     return 0;
  1016. }
  1017.  
  1018. OSErr GDReset(GDHandle device, short *modePtr, short *pagePtr, Ptr *baseAddrPtr)
  1019. /*
  1020. Initialize the video card to its startup state, usually 1 bit per pixel. Returns
  1021. the parameters of that state.
  1022. */
  1023. {
  1024.     VDPageInfo myVDPageInfo;
  1025.     int error;
  1026.  
  1027.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1028.     myVDPageInfo.csMode= *modePtr;
  1029.     myVDPageInfo.csPage= *pagePtr;
  1030.     error=GDControl((*device)->gdRefNum,cscReset,(Ptr) &myVDPageInfo);
  1031.     *modePtr=myVDPageInfo.csMode;
  1032.     *pagePtr=myVDPageInfo.csPage;
  1033.     if(baseAddrPtr!=NULL) *baseAddrPtr=myVDPageInfo.csBaseAddr;
  1034.     return error;
  1035. }
  1036.  
  1037. OSErr GDSetMode(GDHandle device,short mode,short page,Ptr *baseAddrPtr)
  1038. {
  1039.     VDPageInfo myVDPageInfo;
  1040.     int error;
  1041.  
  1042.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1043.     myVDPageInfo.csMode=mode;
  1044.     myVDPageInfo.csPage=page;
  1045.     error=GDControl((*device)->gdRefNum,cscSetMode,(Ptr) &myVDPageInfo);
  1046.     if(baseAddrPtr!=NULL) *baseAddrPtr=myVDPageInfo.csBaseAddr;
  1047.     return error;
  1048. }
  1049.  
  1050. OSErr GDSetEntriesByType(GDHandle device,short start,short count,ColorSpec *table)
  1051. // Calls GDSetEntries or GDDirectSetEntries or nothing, as appropriate.
  1052. // Assumes that the GDevice record is valid, i.e. that the user has not
  1053. // called GDSetMode.
  1054. {
  1055.     switch((*device)->gdType){
  1056.     case fixedType:
  1057.         return statusErr;
  1058.     case clutType:
  1059.         return GDSetEntries(device,start,count,table);
  1060.     case directType:
  1061.         return GDDirectSetEntries(device,start,count,table);
  1062.     }
  1063.     return 1;
  1064. }
  1065.  
  1066. OSErr GDSetEntriesByTypeHighPriority(GDHandle device,short start,short count
  1067.     ,ColorSpec *table)
  1068. {
  1069.     char priority;
  1070.     int error;
  1071.  
  1072.     priority=7;
  1073.     SwapPriority(&priority);
  1074.     error=GDSetEntriesByType(device,start,count,table);
  1075.     SwapPriority(&priority);
  1076.     return error;
  1077. }
  1078.  
  1079. OSErr GDSetEntries(GDHandle device,short start,short count,ColorSpec *table)
  1080. {
  1081.     VDSetEntryRecord vDSetEntryRecord;
  1082.     int error;
  1083.  
  1084.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1085.     vDSetEntryRecord.csStart=start;
  1086.     vDSetEntryRecord.csCount=count;
  1087.     vDSetEntryRecord.csTable=table;
  1088.     error=GDControl((*device)->gdRefNum,cscSetEntries,(Ptr) &vDSetEntryRecord);
  1089.     return error;
  1090. }
  1091.  
  1092. OSErr GDSetGamma(GDHandle device, GammaTbl *gamma)
  1093. {
  1094.     int error;
  1095.     VDGammaRecord myVDGammaRecord;
  1096.  
  1097.     myVDGammaRecord.csGTable=(Ptr)gamma;
  1098.     error=GDControl((*device)->gdRefNum,cscSetGamma,(Ptr) &myVDGammaRecord);
  1099.     return error;
  1100. }
  1101.  
  1102. OSErr GDGrayPage(GDHandle device,short page)
  1103. /*
  1104. Called "GrayScreen" in Designing Cards and Drivers, 3rd Ed. Fills the specified
  1105. page with gray, i.e. the dithered desktop pattern. I'm not aware of any
  1106. particular advantage in using this instead of FillRect().
  1107.  
  1108. Designing Cards and Drivers, 3rd Edition, Chapter 9, says that for direct
  1109. devices, i.e. >8 bit pixels, the driver will also load a linear,
  1110. gamma-corrected, gray color table.
  1111.  
  1112. Contrary to the documentation, version 2 (in System 6.03) of the video driver
  1113. for Apple's old video card requires that one supply the current mode as well.
  1114. Supplying a garbage mode screwed up the screen and soon hung the software. So
  1115. this code first obtains the current mode, and then supplies it in the GrayPage
  1116. Control call.
  1117. */
  1118. {
  1119.     VDPageInfo myVDPageInfo;
  1120.     int error;
  1121.     /* The rest of the arguments are used soley for the bug fix */
  1122.     short mode=0;        /* should be ignored, but isn't */
  1123.     short actualPage;    /* ignored */
  1124.     Ptr baseAddr;        /* ignored */
  1125.  
  1126.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1127.     
  1128.     /* Work around driver bug: get the mode */
  1129.     error=GDGetMode(device,&mode,&actualPage,&baseAddr);
  1130.     if(error)return error;
  1131.     myVDPageInfo.csMode=mode;
  1132.     
  1133.     myVDPageInfo.csPage=page;
  1134.     error=GDControl((*device)->gdRefNum,cscGrayPage,(Ptr) &myVDPageInfo);
  1135.     return error;
  1136. }
  1137.  
  1138. OSErr GDSetGray(GDHandle device,Boolean flag)
  1139. /*
  1140. Tells the driver whether you want colors (flag==0), or prefer that all colors be 
  1141. mapped to luminance-equivalent gray tones? (flag==1).
  1142. */
  1143. {
  1144.     VDFlagRec myVDFlagRec;
  1145.     int error;
  1146.  
  1147.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1148.     myVDFlagRec.flag=flag;
  1149.     error=GDControl((*device)->gdRefNum,cscSetGray,(Ptr) &myVDFlagRec);
  1150.     return error;
  1151. }
  1152.  
  1153. OSErr GDSetInterrupt(GDHandle device,Boolean flag)
  1154. /*
  1155. Set flag to 1 to enable VBL interrupts of this card, or 0 to disable. 
  1156. I don't know when it's appropriate to call this.
  1157. */
  1158. {
  1159.     VDFlagRec myVDFlagRec;
  1160.     int error;
  1161.  
  1162.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1163.     myVDFlagRec.flag=flag;
  1164.     error=GDControl((*device)->gdRefNum,cscSetInterrupt,(Ptr) &myVDFlagRec);
  1165.     return error;
  1166. }
  1167.  
  1168. OSErr GDDirectSetEntries(GDHandle device,short start,short count,ColorSpec *table)
  1169. /*
  1170. If your pixel depth is >8 then the cscSetEntries Control call is disabled, and you use
  1171. cscDirectSetEntries instead. Except for that, GDDirectSetEntries is identical to GDSetEntries.
  1172. */
  1173. {
  1174.     VDSetEntryRecord vDSetEntryRecord;
  1175.     int error;
  1176.  
  1177.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1178.     vDSetEntryRecord.csStart=start;
  1179.     vDSetEntryRecord.csCount=count;
  1180.     vDSetEntryRecord.csTable=table;
  1181.     error=GDControl((*device)->gdRefNum,cscDirectSetEntries,(Ptr) &vDSetEntryRecord);
  1182.     return error;
  1183. }
  1184.  
  1185. OSErr GDSetDefaultMode(GDHandle device,short mode)
  1186. /*
  1187. Supposedly, you tell it what mode you want to start up with when you reboot.
  1188. (I've never been able to get this to work. No error and no effect. Perhaps I've
  1189. misunderstood its purpose.)
  1190. */
  1191. {
  1192.     VDDefModeRec myVDDefModeRec;
  1193.     int error;
  1194.  
  1195.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1196.     myVDDefModeRec.spID=mode;
  1197.     error=GDControl((*device)->gdRefNum,cscSetDefaultMode,(Ptr) &myVDDefModeRec);
  1198.     return error;
  1199. }
  1200.  
  1201. OSErr GDGetMode(GDHandle device,short *modePtr,short *pagePtr,Ptr *baseAddrPtr)
  1202. /*
  1203. It tells you the current mode, page of video memory, and the base address of that
  1204. page.
  1205. */
  1206. {
  1207.     VDPageInfo myVDPageInfo;
  1208.     int error;
  1209.  
  1210.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1211.     error=GDStatus((*device)->gdRefNum,cscGetMode,(Ptr) &myVDPageInfo);
  1212.     if(modePtr!=NULL)*modePtr=myVDPageInfo.csMode;
  1213.     if(pagePtr!=NULL)*pagePtr=myVDPageInfo.csPage;
  1214.     if(baseAddrPtr!=NULL) *baseAddrPtr=myVDPageInfo.csBaseAddr;
  1215.     return error;
  1216. }
  1217.  
  1218. OSErr GDGetEntries(GDHandle device,short start,short count,ColorSpec *table)
  1219. /*
  1220. This is much as you'd expect after reading GDSetEntries above. Note that unless
  1221. the gamma table is linear, the values returned may not be the same as those
  1222. originally passed by GDSetEntries. So call GDUncorrectedGamma first. Note that
  1223. version 2 (in System 6.03) of the video driver for Apple's old video card had a
  1224. bug and did not support "indexed" mode, i.e. start==-1. This is fixed in System
  1225. 6.05. Apple's .Display_Video_Apple_RBV1 v. 0 video driver (built-in to Mac IIci)
  1226. crashes if you attempt to make this call. However, that's a thing of the past,
  1227. because we now first patch the driver to fix the bug. Try the demo TimeVideo.
  1228. */
  1229. {
  1230.     VDSetEntryRecord vDSetEntryRecord;
  1231.     int error;
  1232.     static int bugsPatched=0;
  1233.     unsigned char *name;
  1234.     int version;
  1235.  
  1236.     if(device==NULL || (*device)->gdRefNum==0)return statusErr;
  1237.     if(!bugsPatched){
  1238.         PatchMacIIciVideoDriver();
  1239.         bugsPatched=1;
  1240.     }
  1241.  
  1242.     // Contrary to Apple's rules, these drivers crash if we attempt
  1243.     // a getEntries call. So let's be polite and instead simply return
  1244.     // an error message indicating that this call is not available.
  1245.     name=GDName(device);
  1246.     version=GDVersion(device);
  1247.     if(EqualString(name,"\p.Display_Video_Apple_RBV1",1,1) && version==0)return statusErr;
  1248.     if(EqualString(name,"\p.Color_Video_Display",1,1) && version==9288)return statusErr;
  1249.     if(EqualString(name,"\p.Display_Video_Apple_DOMEMax",1,1) && version==2)return statusErr;
  1250.     vDSetEntryRecord.csStart=start;
  1251.     vDSetEntryRecord.csCount=count;
  1252.     vDSetEntryRecord.csTable=table;
  1253.     error=GDStatus((*device)->gdRefNum,cscGetEntries,(Ptr) &vDSetEntryRecord);
  1254.     return error;
  1255. }
  1256.  
  1257. OSErr GDGetPageCnt(GDHandle device,short mode,short *pagesPtr)
  1258. /*
  1259. Called "GetPages" in Designing Cards and Drivers, 3rd Ed. You tell it what mode
  1260. you're interested in. It tells you how many pages of video ram are available.
  1261. */
  1262. {
  1263.     VDPageInfo myVDPageInfo;
  1264.     int error;
  1265.  
  1266.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1267.     myVDPageInfo.csMode=mode;
  1268.     error=GDStatus((*device)->gdRefNum,cscGetPageCnt,(Ptr) &myVDPageInfo);
  1269.     if(!error)*pagesPtr=myVDPageInfo.csPage;
  1270.     return error;
  1271. }
  1272.  
  1273. OSErr GDGetPageBase(GDHandle device,short page,Ptr *baseAddrPtr)
  1274. /*
  1275. Called "GetBaseAddr" in Designing Cards and Drivers, 3rd Ed. You tell it what
  1276. page of video memory you're interested in (in the current video mode). It tells
  1277. you the base address of that page.
  1278. */
  1279. {
  1280.     VDPageInfo myVDPageInfo;
  1281.     int error;
  1282.  
  1283.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1284.     myVDPageInfo.csPage=page;
  1285.     error=GDStatus((*device)->gdRefNum,cscGetPageBase,(Ptr) &myVDPageInfo);
  1286.     if(baseAddrPtr!=NULL) *baseAddrPtr=myVDPageInfo.csBaseAddr;
  1287.     return error;
  1288. }
  1289.  
  1290. OSErr GDGetGray(GDHandle device,Boolean *flagPtr)
  1291. // It tells you what the flag is set to. Do you want colors? (flag==0) Or do you
  1292. // want all colors mapped to luminance-equivalent gray tones? (flag==1).
  1293. {
  1294.     VDFlagRec myVDFlagRec;
  1295.     int error;
  1296.  
  1297.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1298.     error=GDStatus((*device)->gdRefNum,cscGetGray,(Ptr) &myVDFlagRec);
  1299.     *flagPtr=myVDFlagRec.flag;
  1300.     return error;
  1301. }
  1302.  
  1303. OSErr GDGetInterrupt(GDHandle device,Boolean *flagPtr)
  1304. // Get flag. 1 if VBL interrupts of this card are enabled. 0 if disabled. 
  1305. {
  1306.     VDFlagRec myVDFlagRec;
  1307.     int error;
  1308.  
  1309.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1310.     error=GDStatus((*device)->gdRefNum,cscGetInterrupt,(Ptr) &myVDFlagRec);
  1311.     *flagPtr=myVDFlagRec.flag;
  1312.     return error;
  1313. }
  1314.  
  1315. OSErr GDGetGamma(GDHandle device,GammaTbl **myGammaTblHandle)
  1316. /*
  1317. Returns a pointer to the Gamma table in the specified video device. (I.e. you
  1318. pass it a pointer to your pointer, a handle, which it uses to load your
  1319. pointer.)
  1320.  
  1321. Note that version 2 (in System ≤6.03) of the video driver for Apple's old video
  1322. card does not support this call due to a bug in the driver code. The later
  1323. versions of the driver (3, 4, and 5, in System 6.04 and later) work correctly.
  1324. */
  1325. {
  1326.     int error;
  1327.     VDGammaRecord myVDGammaRecord;
  1328.  
  1329.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1330.     myVDGammaRecord.csGTable=NULL;    // default address is NULL
  1331.     error=GDStatus((*device)->gdRefNum,cscGetGamma,(Ptr) &myVDGammaRecord);
  1332.     *myGammaTblHandle=(GammaTblPtr)myVDGammaRecord.csGTable;
  1333.     return error;
  1334. }
  1335.  
  1336. OSErr GDGetDefaultMode(GDHandle device,short *modePtr)
  1337. // It tells you what the default mode is. I'm not sure what this means.
  1338. {
  1339.     VDDefModeRec myVDDefModeRec;
  1340.     int error;
  1341.  
  1342.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1343.     error=GDStatus((*device)->gdRefNum,cscGetDefaultMode,(Ptr) &myVDDefModeRec);
  1344.     *modePtr=(unsigned char)myVDDefModeRec.spID;
  1345.     return error;
  1346. }
  1347.  
  1348. OSErr GDControl(int refNum,int csCode,Ptr csParamPtr)
  1349. // Uses low-level PBControl() call to implement a "Control()" call that works! 
  1350. // I don't know why this wasn't discussed in Apple Tech Note 262.
  1351. {
  1352.     CntrlParam control;
  1353.     int error;
  1354.     
  1355.     control.ioCompletion=NULL;
  1356.     control.ioCRefNum=refNum;
  1357.     control.csCode=csCode;
  1358.     *((Ptr *) &control.csParam[0]) = csParamPtr;
  1359.     error=PBControl((ParmBlkPtr) &control,0);
  1360.     return error;
  1361. }
  1362.  
  1363. OSErr GDStatus(int refNum,int csCode,Ptr csParamPtr)
  1364. // Uses low-level PBStatus() call to implement a "Status()" call that works! The
  1365. // need for this is explained in Apple Tech Note 262, which was issued in response
  1366. // to my bug report in summer of '89.
  1367. {
  1368.     CntrlParam control;
  1369.     int error;
  1370.     
  1371.     control.ioCompletion=NULL;
  1372.     control.ioCRefNum=refNum;
  1373.     control.csCode=csCode;
  1374.     *((Ptr *) &control.csParam[0]) = csParamPtr;
  1375.     error=PBStatus((ParmBlkPtr) &control,0);
  1376.     return error;
  1377. }
  1378.  
  1379. #if 0
  1380. /*
  1381. From: absurd@apple.apple.com (Tim Dierks, software saboteur)
  1382. Date: Fri, 20 Nov 1992 00:38:14 GMT
  1383. Organization: MacDTS Marauders
  1384.  
  1385. Here's the right way to get the slot number of a monitor, given its
  1386. GDevice:  (as a bonus, this also gets the name of the card in
  1387. question; to just get the slot, chop off all the lines after the
  1388. *slot = ... line.
  1389. */
  1390.  
  1391. OSErr GetSlotAndName(GDHandle gDev,short *slot,char *name)
  1392. {   OSErr       err;
  1393.     short       refNum;
  1394.     SpBlock     spb;
  1395.     
  1396.     refNum = (**gDev).gdRefNum;    // video driver refNum for this GDevice
  1397.     *slot = (**(AuxDCEHandle)GetDCtlEntry(refNum)).dCtlSlot;
  1398.                                    // slot in which this video card sits
  1399.     spb.spSlot = *slot;         // In the slot we're interested in
  1400.     spb.spID = 0;
  1401.     spb.spExtDev = 0;
  1402.     spb.spCategory = 1;         // Get the board sResource
  1403.     spb.spCType = 0;
  1404.     spb.spDrvrSW = 0;
  1405.     spb.spDrvrHW = 0;
  1406.     spb.spTBMask = 0;
  1407.     err = SNextTypeSRsrc(&spb);
  1408.     if (err)return err;
  1409.     spb.spID = 2;               // Getting the description string
  1410.                                 // spSPointer was set up by SNextTypesResource
  1411.     err = SGetCString(&spb);
  1412.     if (err)return err;
  1413.     strcpy(name,(char *)spb.spResult);  // Get the returned string
  1414.     DisposPtr((Ptr)spb.spResult);    // Undocumented; we have to dispose of it
  1415.     c2pstr(name);
  1416.     return noErr;
  1417. }
  1418. #endif
  1419.  
  1420. char *GDCardName(GDHandle device)
  1421. /*
  1422. Returns the address of a C string containing the name of the video card. You
  1423. should call DisposPtr() on the returned address when you no longer need it.
  1424. Takes about 1.5 ms; I don't know why Apple's slot routines are so slow. This
  1425. routine sets up the flags in the SNextTypeSRsrc() call quite differently from
  1426. the above example, but I don't know if that matters, since I've been using this
  1427. routine for a year or so without any problems.
  1428. */
  1429. {
  1430.     AuxDCE **auxDCEHandle;
  1431.     SpBlock SPB,SPB1;
  1432.     
  1433.     if(device==NULL || (*device)->gdRefNum==0)return "";
  1434.     auxDCEHandle = (AuxDCE **) GetDCtlEntry((*device)->gdRefNum);
  1435.     SPB.spSlot = (**auxDCEHandle).dCtlSlot;
  1436.     SPB.spCategory = 0;
  1437.     SPB.spCType =     0;
  1438.     SPB.spDrvrSW =     0;
  1439.     SPB.spDrvrHW =     1;
  1440.     SPB.spTBMask = 0xf;
  1441.     SPB.spID = 0;
  1442.     SPB.spExtDev = 0;
  1443.     if(SNextTypeSRsrc(&SPB) == noErr) {
  1444.         SPB1.spsPointer = SPB.spsPointer;
  1445.         SPB1.spID = 2;
  1446.         SGetCString(&SPB1);
  1447.         return (char *)SPB1.spResult;
  1448.     }
  1449.     else return "";
  1450. }
  1451.  
  1452. unsigned char *GDName(GDHandle device)
  1453. // Returns a pointer to the name of the driver (a pascal string). 
  1454. {
  1455.     VideoDriver *videoDriverPtr;
  1456.  
  1457.     if(device==NULL || (*device)->gdRefNum==0)return "\p";
  1458.     videoDriverPtr=GDDriverAddress(device);
  1459.     return videoDriverPtr->name;
  1460. }
  1461.  
  1462. char *GDNameStr(GDHandle device)
  1463. // Returns the driver name as a C string.
  1464. {
  1465.     unsigned char *sp;
  1466.     static char name[32];
  1467.     
  1468.     sp=GDName(device);
  1469.     memcpy(name,sp,sp[0]+1);
  1470.     return p2cstr((unsigned char *)name);
  1471. }
  1472.  
  1473.  
  1474. int GDVersion(GDHandle device)
  1475. // Returns the version number of the driver. From the first word-aligned word after
  1476. // the name string.
  1477. {
  1478.     int version;
  1479.     unsigned char *bytePtr;
  1480.  
  1481.     if(device==NULL || (*device)->gdRefNum==0)return 0;
  1482.     bytePtr=GDName(device);
  1483.     bytePtr += 1+bytePtr[0];    /* go to end of Pascal string */
  1484.     bytePtr = (unsigned char *)((long)(bytePtr+1) & ~1);    // round up to word boundary
  1485.     version = *(short *)bytePtr;
  1486.     return version;
  1487. }
  1488.  
  1489. VideoDriver *GDDriverAddress(GDHandle device)
  1490. // Returns a pointer to the driver, whether in ROM or RAM. 
  1491. {
  1492.     AuxDCE **auxDCEHandle;
  1493.     VideoDriver *videoDriverPtr;
  1494.  
  1495.     if(device==NULL || (*device)->gdRefNum==0)return NULL;
  1496.     auxDCEHandle = (AuxDCE **) GetDCtlEntry((*device)->gdRefNum);
  1497.     if((**auxDCEHandle).dCtlFlags & dRAMBased){
  1498.         /* RAM-based driver. */
  1499.         videoDriverPtr=*(VideoDriver **) (**auxDCEHandle).dCtlDriver;
  1500.     }
  1501.     else{
  1502.         /* ROM-based driver. */
  1503.         videoDriverPtr=(VideoDriver *) (**auxDCEHandle).dCtlDriver;
  1504.     }
  1505.     return videoDriverPtr;
  1506. }
  1507.  
  1508. /*
  1509. ROUTINE: PatchMacIIciVideoDriver
  1510. PURPOSE:
  1511. It is unlikely that you will need to call this explicitly, because it is called
  1512. automatically by GDGetEntries the first time it is invoked, and the sole purpose
  1513. of this routine is to fix a driver bug that would cause a crash when called by
  1514. GDGetEntries.
  1515.  
  1516. The Mac IIci built-in video driver (.Display_Video_Apple_RBV1 driver, version 0)
  1517. has a bug that causes it to crash if you try to do a getEntries Status request.
  1518. PatchMacIIciVideoDriver() will find and patch the memory-resident copy of the
  1519. buggy driver. Only two instructions are modified, to save and restore more
  1520. registers. This fix persists only until the next reboot. If the patch is
  1521. successfully applied the version number is increased from 0 to 100, to
  1522. distinguish it from versions 0 and 1.
  1523.  
  1524. A returned value of 1 indicates success: the needed patch was applied, either now
  1525. or previously. A return value of 0 indicates no patch was needed.
  1526.  
  1527. This patch is based on a comparison of the version 0 and 1 drivers used by the
  1528. Mac IIci and IIsi, respectively. The patch changes a pair of save and restore
  1529. operations (MOVEM.L to and from the stack) to save and restore registers D1 and
  1530. A1 as well as D4, A3, and A4. There are many other differences between versions
  1531. 0 and 1 of the driver, but this change is enough to keep the version 0 driver
  1532. from crashing when we attempt to read the clut by calling GDGetEntries.
  1533.  
  1534. The only change that the Mac operating system could possibly notice is that,
  1535. when we're done patching, we set the handle to be non-purgeable, since purging
  1536. and reloading the driver would eliminate the patch.
  1537.  
  1538. edward_de_Jong@bmug.org and Robert Savoy (SAVOY@RISVAX.ROWLAND.ORG) reported
  1539. that their Mac IIci computers' built-in video driver is ROM-based, so
  1540. PatchMacIIciVideoDriver was enhanced to deal with a ROM-based driver, by copying
  1541. the driver into RAM, making that the active driver, and patching it. Robert
  1542. Savoy reports that it works fine.
  1543.  
  1544. An alternative, permanent, solution is described in the file "Video synch":
  1545. upgrading to Apple's bug-free version 1 of the driver. However, that solution
  1546. only works if the Mac IIci has more than one monitor.
  1547.  
  1548. */
  1549.  
  1550. int PatchMacIIciVideoDriver(void)
  1551. {
  1552.     GDHandle device;
  1553.     short *w;
  1554.     AuxDCE **auxDCEHandle;
  1555.     Handle handle;
  1556.     enum{badVersion=0};
  1557.     int error;
  1558.     long value;
  1559.     
  1560.     error=Gestalt(gestaltQuickdrawVersion,&value);
  1561.     if(error || value<gestalt8BitQD)return 0;    // need 8-bit quickdraw
  1562.     device = GetDeviceList();
  1563.     while(1) {
  1564.         if(device==NULL || (*device)->gdRefNum==0)return 0;
  1565.         if (!TestDeviceAttribute(device,screenDevice)
  1566.             || !TestDeviceAttribute(device,screenActive)){
  1567.             device=GetNextDevice(device);
  1568.             continue;
  1569.         }
  1570.         if(EqualString("\p.Display_Video_Apple_RBV1",GDName(device),1,1))
  1571.             switch(GDVersion(device)){
  1572.                 case badVersion:
  1573.                     break;
  1574.                 case badVersion+100:    // already patched
  1575.                     return 1;
  1576.                 default:
  1577.                     return 0;
  1578.         }else{
  1579.             device=GetNextDevice(device);
  1580.             continue;
  1581.         }
  1582.         break;
  1583.     }
  1584.     auxDCEHandle = (AuxDCE **) GetDCtlEntry((*device)->gdRefNum);
  1585.     
  1586.     // Move ROM-based driver into RAM.
  1587.     if(!((**auxDCEHandle).dCtlFlags & dRAMBased)){
  1588.         long bytes;
  1589.         VideoDriver *driver;
  1590.         
  1591.         driver=(VideoDriver *)(**auxDCEHandle).dCtlDriver;
  1592.         // Sometimes the word preceding the driver in ROM seems to be the
  1593.         // driver size, but not always, e.g. the built-in driver on the Mac IIsi.
  1594.         bytes=*((short *)driver-1);
  1595.         // Driver size unknown, guessing (generously) at twice the highest offset.
  1596.         bytes=driver->open;
  1597.         if(bytes<driver->prime)bytes=driver->prime;
  1598.         if(bytes<driver->control)bytes=driver->control;
  1599.         if(bytes<driver->status)bytes=driver->status;
  1600.         if(bytes<driver->close)bytes=driver->close;
  1601.         bytes*=2;
  1602.         // We know the Mac IIci driver size to be 1896
  1603.         // when ROM version is 124 rev. 1, but who knows for later ROMs?
  1604.         //bytes=1896;
  1605.         handle=NewHandleSys(bytes);
  1606.         if(handle==NULL)return 0;    // Insufficient room on System heap.
  1607.         HLockHi(handle);
  1608.         BlockMove((Ptr)driver,*handle,bytes);
  1609.         (**auxDCEHandle).dCtlDriver=(Ptr)handle;
  1610.         (**auxDCEHandle).dCtlFlags |= dRAMBased;        
  1611.     }
  1612.     
  1613.     // Patch RAM-based driver.
  1614.     handle=(Handle)(**auxDCEHandle).dCtlDriver;
  1615.     w=*(short **)handle;
  1616.     if(w[0x51e/2]!=0x818 || w[0x590/2]!=0x1810 || w[0x2c/2]!=badVersion){
  1617.         printf("PatchMacIIciVideoDriver error.\n");
  1618.         return 0;
  1619.     }
  1620.     w[0x51e/2]=0x4858;
  1621.     w[0x590/2]=0x1a12;
  1622.     w[0x2c/2]+=100;                                    // Change version number.
  1623.     if(w[0x51e/2]!=0x4858 || w[0x590/2]!=0x1a12){
  1624.         printf("PatchMacIIciVideoDriver error.\n");
  1625.         return 0;
  1626.     }
  1627.     HNoPurge(handle);
  1628.     return 1;
  1629. }
  1630.